# coding=utf-8
import datetime
import os
import threading
from queue import Queue

import pandas as pd
from loguru import logger

import const
from cal_ops.point import cal_point1_down
from models.stock_model import StockNumber
from mylib.download_all import analysis_stock
from mylib.mycsv import sort_csv

st_queue = Queue()


def t_download(stocks, d):
    try:
        df = pd.read_csv('all.csv')
        for row in df.index:
            if stocks and df.loc[row]['ts_code'] not in stocks:
                continue
            sn = StockNumber(df.loc[row])
            if '退' in sn.name:
                continue
            if 'ST' in sn.name:
                continue
            if not str(sn.ts_code).startswith('60') \
                    and not str(sn.ts_code).startswith('00'):
                continue
            if d:
                analysis_stock(sn)
            st_queue.put(('cal_aa', 1, [sn.ts_code]))
    except Exception as e:
        logger.error(e)
    st_queue.put((1, 1, 1))


def t_cal(bkd, full_path_csv, end_date):
    log_dir = os.path.basename(__file__).split('.')[0]
    current_date = str(datetime.datetime.now().date()).replace('-', '')
    log_dir = f'{log_dir}/{current_date}'
    start_date = 20991230
    with open(full_path_csv, 'w', encoding='utf-8') as aa:
        aa.write(f'AA,BB,CC,DD')
        while 1:
            if not st_queue:
                continue
            indus, indus_num, stocks = st_queue.get()
            if (1, 1, 1) == (indus, indus_num, stocks):
                logger.warning('所有计算完成')
                break
            logger.info(f'开始计算{stocks}')
            trade_date_dict = cal_point1_down.run(log_dir, start_date, end_date, stocks=stocks, bkd=bkd)
            for k, v in trade_date_dict.items():
                aa.write(f'\n{k},{v}')


def run(stocks=None, d=True):
    logger.add("log/main_cal_today_{time}.log", level='WARNING')
    current_date = datetime.date.today()
    full_path_csv = f'aa_down_{current_date}.csv'
    end_date = 20240205
    bkd = 100
    t1 = threading.Thread(target=t_download, args=(stocks, d,))
    t2 = threading.Thread(target=t_cal, args=(bkd, full_path_csv, end_date,))
    t2.start()
    t1.start()
    t2.join()
    t1.join()
    sort_csv(full_path_csv, ['AA', 'BB'], [False, False])


if __name__ == '__main__':
    stocks = const.stocks
    run()
